package com.ssyt.hiring.common;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ssyt.hiring.company.entity.PositionEntity;
import com.ssyt.hiring.company.service.PositionService;
import com.ssyt.hiring.talent.service.TalentService;

public class CommonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private TalentService talentService = new TalentService();
	private CommonService commonService = new CommonService();
	private PositionService positionService = new PositionService();

	public CommonServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODE_UTF8);
		String command = request.getParameter("command");
		if ("toForgetPasswordUI".equals(command)) {
			toForgetPasswordUI(request, response);
		} else if ("sendEmail".equals(command)) {
			sendEmail(request, response);
		} else if ("toUpdatePasswordUI".equals(command)) {
			toUpdatePasswordUI(request, response);
		} else if ("updatePassword".equals(command)) {
			updatePassword(request, response);
		} else if ("toMainUI".equals(command)) {
			toMainUI(request, response);
		} else if ("loadingData".equals(command)) {
			loadingData(request, response);
		} else {
			throw new IllegalStateException("请求非法~");
		}
	}

	/**
	 * 查询所有招聘职位并跳转到主页
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toMainUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int pageNo = Constants.DEFAULT_PAGE_NO;
		int pageSize = Constants.DEFAULT_PAGE_SIZE;
		String pageNoStr = request.getParameter("pageNo");
		String searchText = request.getParameter("searchText");
		if (pageNoStr != null) {
			pageNo = Integer.parseInt(pageNoStr);
		}
		String pageSizeStr = request.getParameter("pageSize");
		if (pageSizeStr != null) {
			pageSize = Integer.parseInt(pageSizeStr);
		}
		PageModel<PositionEntity> pageModel = positionService.list(searchText,
				pageNo, pageSize);
		request.setAttribute("pageModel", pageModel);
		request.setAttribute("searchText", searchText);
		request.getRequestDispatcher("WEB-INF/views/common/main.jsp").forward(
				request, response);
	}

	/**
	 * 转到找回密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toForgetPasswordUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(
				"/WEB-INF/views/common/forget-password.jsp").forward(request,
				response);
	}

	/**
	 * 发送密码重置邮件
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void sendEmail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		String validateCode = request.getParameter("validateCode");
		String sessionValidateCode = (String) request.getSession()
				.getAttribute(
						com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		// 1、验证码判断
		if (validateCode.equals(sessionValidateCode)) {

			boolean result = talentService.isExisEmail(accountType, email);
			if (result) {
				boolean sendResult = commonService.send(email, accountType);
				if (sendResult) {
					request.setAttribute("msg", "邮件已发送到邮箱，请查看");
					request.getRequestDispatcher(
							"/WEB-INF/views/" + accountType + "/" + accountType
									+ "-login.jsp").forward(request, response);
				} else {
					request.setAttribute("msg", "邮件发送失败！");
					toForgetPasswordUI(request, response);
				}
			} else {
				request.setAttribute("msg", "没有此邮箱！");
				toForgetPasswordUI(request, response);
			}
		} else {
			request.setAttribute("msg", "验证码输入错误！");
			request.setAttribute("email", email);
			toForgetPasswordUI(request, response);
		}
	}

	/**
	 * 转到修改密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toUpdatePasswordUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		boolean result = talentService.isEmailLinkExpired(email, accountType);
		if (result) {
			request.getRequestDispatcher(
					"/WEB-INF/views/common/update-password-fail.jsp").forward(
					request, response);
		} else {
			String securityKey = request.getParameter("securityKey");
			boolean matchedResult = talentService.isMatched(email, accountType,
					securityKey);
			if (matchedResult) {
				request.getRequestDispatcher(
						"/WEB-INF/views/common/update-password.jsp").forward(
						request, response);
			} else {
				request.getRequestDispatcher(
						"/WEB-INF/views/common/update-password-fail.jsp")
						.forward(request, response);
			}
		}
	}

	/**
	 * 修改密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		String newPassword = request.getParameter("newPassword");
		talentService.updatePassword(accountType, email, newPassword);

		request.setAttribute("msg", "密码重置成功！");
		request.getRequestDispatcher(
				"/WEB-INF/views/" + accountType + "/" + accountType
						+ "-login.jsp").forward(request, response);
	}

	/**
	 * 滚动加载
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void loadingData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int pageNo = Constants.DEFAULT_PAGE_NO;
		int pageSize = Constants.DEFAULT_PAGE_SIZE;
		String pageNoStr = request.getParameter("pageNo");
		String searchText = request.getParameter("searchText");
		if (pageNoStr != null) {
			pageNo = Integer.parseInt(pageNoStr);
		}
		String pageSizeStr = request.getParameter("pageSize");
		if (pageSizeStr != null) {
			pageSize = Integer.parseInt(pageSizeStr);
		}
		PageModel<PositionEntity> pageModel = positionService.list(searchText,
				pageNo, pageSize);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().print(
				JSON.toJSONStringWithDateFormat(pageModel,
						"yyyy-MM-dd HH:mm:ss",
						SerializerFeature.WriteDateUseDateFormat));
	}

}
